import { createI18n, type Locale } from 'vue-i18n';
import type { ImportLocaleFn } from "@/typings/locale"
import antdEnLocale from 'ant-design-vue/es/locale/en_US';
import antdDefaultLocale from 'ant-design-vue/es/locale/zh_CN';
import dayjs from 'dayjs';

export const i18n = createI18n({
  globalInjection: true,
  locale: 'zh-CN',
  messages: {},
});

export const $t = i18n.global.t;

// @ts-ignore
const locale = ref<Locale>(antdDefaultLocale);

/**
 * Load locale modules with directory structure
 * @param regexp - Regular expression to match language and file names
 * @param modules - The modules object containing paths and import functions
 * @returns A map of locales to their corresponding import functions
 */
export function loadLocalesMapFromDir(
  regexp: RegExp,
  modules: Record<string, () => Promise<unknown>>,
): Record<Locale, ImportLocaleFn> {
  const localesRaw: Record<Locale, Record<string, () => Promise<unknown>>> = {};
  const localesMap: Record<Locale, ImportLocaleFn> = {};

  // Iterate over the modules to extract language and file names
  for (const path in modules) {
    const match = path.match(regexp);
    if (match) {
      const [_, locale, fileName] = match;
      if (locale && fileName) {
        if (!localesRaw[locale]) {
          localesRaw[locale] = {};
        }
        if (modules[path]) {
          localesRaw[locale][fileName] = modules[path];
        }
      }
    }
  }

  // Convert raw locale data into async import functions
  for (const [locale, files] of Object.entries(localesRaw)) {
    localesMap[locale] = async () => {
      const messages: Record<string, any> = {};
      for (const [fileName, importFn] of Object.entries(files)) {
        messages[fileName] = ((await importFn()) as any)?.default;
      }
      return { default: messages };
    };
  }

  return localesMap;
}

/**
 * 加载dayjs的语言包
 * @param lang
 */
export async function loadDayjsLocale(lang: string) {
  let dayLocale: any;
  switch (lang) {
    case 'en-US': {
      // @ts-ignore
      dayLocale = await import('dayjs/locale/en');
      break;
    }
    case 'zh-CN': {
      // @ts-ignore
      dayLocale = await import('dayjs/locale/zh-cn');
      break;
    }
    // 默认使用英语
    default: {
      // @ts-ignore
      dayLocale = await import('dayjs/locale/zh-cn');
    }
  }
  if (dayLocale) {
    dayjs.locale(dayLocale);
  } else {
    console.error(`Failed to load dayjs locale for ${lang}`);
  }
}

/**
 * 加载antd的语言包
 * @param lang
 */
export async function loadAntdLocale(lang: string) {
  switch (lang) {
    case 'en-US': {
      // @ts-ignore
      locale.value = antdEnLocale;
      break;
    }
    case 'zh-CN': {
      // @ts-ignore
      locale.value = antdDefaultLocale;
      break;
    }
  }
}

export {
  locale
}